using UnityEngine;
using System.Collections.Generic;

public class Waypoint : MonoBehaviour {

	public class Edge {
		public Waypoint wp;
		public float dist;
	}

	public List<Edge> edges;

	public Waypoint[] GetNeighbours() {
		List<Waypoint> n = new List<Waypoint>();

		foreach(Edge e in edges) {
			n.Add(e.wp);
		}

		return n.ToArray();
	}

	// Use this for initialization
	void Start () {

		edges = new List<Edge>();

		Waypoint[] wps = GameObject.FindObjectsOfType<Waypoint>();

		foreach(Waypoint wp in wps) {
			if(wp == this)
				continue;

			RaycastHit2D[] hits = Physics2D.LinecastAll(transform.position, wp.transform.position, 1 << 0);

			bool didHit = false;
			foreach(RaycastHit2D hit in hits) {
				if( hit.collider == null || hit.collider == wp.collider2D || hit.collider == this.collider2D) {
					// skip
				}
				else {
					didHit = true;
				}
			}

			if(didHit == false) {
				Edge e = new Edge();
				e.wp = wp;
				e.dist = Vector2.Distance(wp.transform.position, transform.position);
				edges.Add (e);
			}
		}
	}

	void RemoveWaypoint(Waypoint wp) {
		foreach (Edge e in edges) {
			if(e.wp == wp) {
				edges.Remove(e);
				return;
			}
		}
	}

	void OnDestroy() {
		foreach (Edge e in edges) {
			e.wp.RemoveWaypoint(this);
		}
	}

	void Update() {
		foreach (Edge e in edges) {
			Debug.DrawLine(transform.position, e.wp.transform.position);
		}
	}
	
}
